package com.insight.controller;

import com.insight.dto.graph.RelationshipGraph;
import com.insight.service.RelationshipGraphService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

/**
 * T115: 表关系可视化REST API
 * 提供表关系图查询接口
 *
 * 端点列表:
 * - GET /api/v1/relationships/table/{tableId} - 获取单表关系图
 * - GET /api/v1/relationships/datasource/{dataSourceId} - 获取数据源关系图
 *
 * @author Insight Team
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/relationships")
@RequiredArgsConstructor
@Validated
@Tag(name = "表关系可视化", description = "提供表关系图查询和分析功能")
public class RelationshipController {

    private final RelationshipGraphService graphService;

    /**
     * 获取单个表的关系图
     * US5场景1: 查看单表的父子关系
     *
     * @param tableId  表ID
     * @param maxDepth 最大遍历深度(可选,默认5,最大10)
     * @return 关系图
     */
    @GetMapping("/table/{tableId}")
    @Operation(summary = "获取单表关系图", description = "获取指定表的父子关系图,包括所有上下游依赖表")
    public ResponseEntity<RelationshipGraph> getTableRelationshipGraph(
            @Parameter(description = "表ID", required = true)
            @PathVariable Long tableId,
            @Parameter(description = "最大遍历深度(1-10)")
            @RequestParam(required = false, defaultValue = "5")
            @Min(value = 1, message = "最大深度不能小于1")
            @Max(value = 10, message = "最大深度不能超过10")
            Integer maxDepth) {

        log.info("查询表关系图: tableId={}, maxDepth={}", tableId, maxDepth);

        try {
            RelationshipGraph graph = graphService.generateGraphForTable(tableId, maxDepth);
            return ResponseEntity.ok(graph);
        } catch (IllegalArgumentException e) {
            log.warn("表不存在: tableId={}", tableId);
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "表不存在: id=" + tableId, e);
        }
    }

    /**
     * 获取数据源的完整关系图
     * US5场景2: 查看数据源的完整关系网络
     *
     * @param dataSourceId 数据源ID
     * @return 关系图
     */
    @GetMapping("/datasource/{dataSourceId}")
    @Operation(summary = "获取数据源关系图", description = "获取数据源下所有表的完整关系网络")
    public ResponseEntity<RelationshipGraph> getDataSourceRelationshipGraph(
            @Parameter(description = "数据源ID", required = true)
            @PathVariable Long dataSourceId) {

        log.info("查询数据源关系图: dataSourceId={}", dataSourceId);

        RelationshipGraph graph = graphService.generateGraphForDataSource(dataSourceId);
        return ResponseEntity.ok(graph);
    }
}
